package com.sam.im.heiqun.uis.activities;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.MsgEntity;
import com.sam.im.heiqun.sound.ChatCallActivity;
import com.sam.im.heiqun.sound.entity.ConstantApp;
import com.sam.im.heiqun.uis.adapters.ChatRecyclerAdapter;
import com.sam.im.heiqun.utils.ConversationUtils;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.uis.activitys.BaseActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

public class CallFriendAgreeActivity extends BaseActivity {

    public String CALL_FRIEND_TYPE = "VIDEO", CALL_FRIEND_AGIN_TYPE = "VIDEO"; //callType 通话类型 VOICE 语音通话  VIDEO 视频通话
    private String type;//trequest请求
    private LinearLayout ll_call_callResponse;
    private TextView tv_ca_name;
    private Button btn_canale_video, btn_agree_vido, btn_no_vido;
    private String data, friend_id;
    private ConversationUtils conversationUtils;
    private JSONObject jsonObject;
    private MediaPlayer mPlayer;

    @Override
    public int getContentViewId() {
        return R.layout.activity_call_friend;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        ToolsUtils.isConversation = true;
        EventBus.getDefault().register(this);
        data = getIntent().getStringExtra("data");
        if (ChatCallActivity.isActive) {
            friend_id = getSharedPreferences("Demo", Context.MODE_PRIVATE).getString("friend_ids", null);
        }
        try {
            jsonObject = new JSONObject(data);
            if (jsonObject == null) return;
            if ((jsonObject.getInt("fromId") + "").equals("")) return;
            SharedPreferences.Editor editor = getSharedPreferences("Demo", Context.MODE_PRIVATE).edit();
            editor.putString("friend_ids", jsonObject.getInt("fromId") + "");
            editor.commit();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ll_call_callResponse = (LinearLayout) findViewById(R.id.ll_call_callResponse);
        btn_canale_video = (Button) findViewById(R.id.btn_canale_video);
        btn_no_vido = (Button) findViewById(R.id.btn_no_vido);
        btn_agree_vido = (Button) findViewById(R.id.btn_agree_vido);
        tv_ca_name = (TextView) findViewById(R.id.tv_ca_name);
        ll_call_callResponse.setVisibility(View.VISIBLE);
        btn_canale_video.setVisibility(View.GONE);
        btn_canale_video.setOnClickListener(this);

        try {
            if (jsonObject.getInt("messageType") == Constant.TOMessageTypeVoiceRequest) {
                //发起语音
                tv_ca_name.setText(jsonObject.getString("fromName") + "请求发起语音通话");
            } else {
                tv_ca_name.setText(jsonObject.getString("fromName") + "请求发起视频通话");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        btn_no_vido.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ChatCallActivity.isActive) {
                    EventBus.getDefault().post(Constant.TOMessageTypeRefuseVideoRequest);
                    try {
                        if (jsonObject.getInt("messageType") == Constant.TOMessageTypeVoiceRequest) {
                            Log.i("fanhui", "id:" + friend_id);
                            //拒接接受语音
                            acceptCall(Constant.TOMessageTypeRefuseVoiceRequest, Integer.parseInt(friend_id));
                        } else {
                            acceptCall(Constant.TOMessageTypeRefuseVideoRequest, Integer.parseInt(friend_id));
                        }
                        MsgEntity msgEntity = new MsgEntity();
                        msgEntity.setMsgString(getResources().getString(R.string.chat_cancle_refuse));
                        String msg = new Gson().toJson(msgEntity);
                        conversationUtils.sendMsgTime(msg, ChatRecyclerAdapter.TO_USER_EMOJI_TEXT, Integer.parseInt(friend_id));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        if (jsonObject.getInt("messageType") == Constant.TOMessageTypeVoiceRequest) {
                            //拒接接受语音
                            acceptCall(Constant.TOMessageTypeRefuseVoiceRequest, jsonObject.getInt("fromId"));
                        } else {
                            acceptCall(Constant.TOMessageTypeRefuseVideoRequest, jsonObject.getInt("fromId"));
                        }
                        MsgEntity msgEntity = new MsgEntity();
                        msgEntity.setMsgString(getResources().getString(R.string.chat_cancle_refuse));
                        String msg = new Gson().toJson(msgEntity);
                        conversationUtils.sendMsgTime(msg, ChatRecyclerAdapter.TO_USER_EMOJI_TEXT, jsonObject.getInt("fromId"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }


                finish();
            }
        });
        btn_agree_vido.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //同意接受语音


                Intent intent = new Intent(CallFriendAgreeActivity.this, ChatCallActivity.class);

                try {
                    intent.putExtra(ConstantApp.ACTION_KEY_CHANNEL_NAME, jsonObject.getString("content"));
                    intent.putExtra("fromid", jsonObject.getInt("fromId"));
                    intent.putExtra("type", jsonObject.getInt("messageType"));
                    startActivity(intent);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (ChatCallActivity.isActive) {
                    //存在
                    EventBus.getDefault().post(Constant.TOMessageTypeRefuseVideoRequest);
                    try {
                        if (jsonObject.getInt("messageType") == Constant.TOMessageTypeVoiceRequest) {
                            Log.i("fanhui", "id:" + friend_id);
                            //同意接受语音
                            acceptCall(Constant.TOMessageTypeRefuseVoiceRequest, Integer.parseInt(friend_id));
                            acceptCall(Constant.TOMessageTypeAgreeVoiceRequest, jsonObject.getInt("fromId"));
                        } else {
                            acceptCall(Constant.TOMessageTypeRefuseVideoRequest, Integer.parseInt(friend_id));
                            acceptCall(Constant.TOMessageTypeAgreeVideoRequest, jsonObject.getInt("fromId"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {

                    try {

                        if (jsonObject.getInt("messageType") == Constant.TOMessageTypeVoiceRequest) {
                            //拒接接受语音
                            acceptCall(Constant.TOMessageTypeAgreeVoiceRequest, jsonObject.getInt("fromId"));
                        } else {
                            acceptCall(Constant.TOMessageTypeAgreeVideoRequest, jsonObject.getInt("fromId"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }


                finish();
            }
        });
        mPlayer = MediaPlayer.create(this, R.raw.music_callin);
        mPlayer.start();
    }

    /**
     * 同意拒绝音频
     *
     * @param type
     */
    public void acceptCall(int type, int fid) {
        mPlayer.stop();
        try {

            conversationUtils = new ConversationUtils(CallFriendAgreeActivity.this);

            conversationUtils.sendMsg(jsonObject.getString("content"), type, fid);
            mPlayer.stop();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onBaseEvent(final Integer type) {
        if (type == com.sam.im.heiqun.constant.Constant.TOMessageTypeRefuseVideoRequest) {
            mPlayer.stop();
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ToolsUtils.isConversation = false;
        EventBus.getDefault().unregister(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            try {
                if (jsonObject.getInt("messageType") == Constant.TOMessageTypeVoiceRequest) {
                    //拒接接受语音
                    acceptCall(Constant.TOMessageTypeRefuseVoiceRequest, jsonObject.getInt("fromId"));
                } else {
                    acceptCall(Constant.TOMessageTypeRefuseVideoRequest, jsonObject.getInt("fromId"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            mPlayer.stop();
            finish();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }
}
